package org.ala.tiktools.rpc.client_server.service.impls;

import org.ala.tiktools.logs.LoggerFactory;
import org.ala.tiktools.rpc.client_server.service.IRpcServiceReceiver;
import org.ala.tiktools.rpc.client_server.service.RpcServiceExecutor;
import org.slf4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import io.netty.channel.Channel;

/**
 * 消息接收器
 *
 * @author ala
 * @date 2025-04-07 14:52
 */
public abstract class AbstractRpcServiceReceiver implements IRpcServiceReceiver, ApplicationContextAware {


    static Logger log = LoggerFactory.getLogger("rpc", "init");


    /**
     *
     */
    protected ApplicationContext context;


    /**
     * 执行器
     */
    protected RpcServiceExecutor executor;
    /**
     *  主channel
     */
    protected Channel mainChannel;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;

        mainChannel = init(applicationContext);
        log.info("[{} init] netty服务端开启", this.getClass().getSimpleName());
    }
    /**
     *  初始化接收器
     */
    public abstract Channel init(ApplicationContext applicationContext);


    public RpcServiceExecutor getExecutor() {
        return executor;
    }

    @Override
    public void setExecutor(RpcServiceExecutor serviceExecutor) {
        this.executor = serviceExecutor;
    }

    /**
     *  销毁回调
     */
    @Override
    public void destroy() throws Exception {
        if (mainChannel != null) {
            log.info("[{} init] netty服务端销毁", this.getClass().getSimpleName());
            mainChannel.close().sync();
        }
    }

    /**
     *  当有新的客户端连接时
     *  <p> channel被注册到EventLoop时
     */
    protected void channelRegistered(Channel channel) {}
    /**
     *  当有链接关闭时
     *  <p> channel从EventLoop上解绑
     */
    protected void channelUnRegistered(Channel channel) {}
}
